package com.example.runningman.user;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.runningman.MainActivity;
import com.example.runningman.R;
import com.example.runningman.bean.User;
import com.example.runningman.util.SPUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

public class ChangepswActivity extends AppCompatActivity {
    String phone;
    TextView textView;
    EditText codee;
    EditText psw;
    EditText repsw;
    ImageButton back;
    Button btn;
    String code;
    Button reg;
    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_changepsw);
        textView=findViewById(R.id.phoneNumber);
        codee=findViewById(R.id.yanZhengMaText);
        psw=findViewById(R.id.reg_password);
        repsw=findViewById(R.id.reg_repassword);
        btn=findViewById(R.id.queRenXiuGaiBtn);
        back=findViewById(R.id.back3);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(ChangepswActivity.this,MainActivity.class);
                startActivity(intent);
            }
        });
        reg=findViewById(R.id.reg);
        mHandler = new Mhandler(this);
        phone=SPUtil.getInstance(getApplicationContext()).getString("phone");

        reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postRequestCode(phone);
                reg.setEnabled(false);
                reg.setBackgroundResource(R.color.darkgrey);
                timerTest();
            }
        });
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if("".equals(psw.getText().toString())||"".equals(repsw.getText().toString())||"".equals(codee.getText().toString())){
                    Toast.makeText(getApplicationContext(),"输入完整信息",Toast.LENGTH_SHORT).show();
                }else{
                    if(repsw.getText().toString().equals(psw.getText().toString())){
                        code=SPUtil.getInstance(getApplicationContext()).getString("code","ssdasd");
                        if(code.equals(codee.getText().toString())){
                            postRequest(psw.getText().toString());
                        }else{
                            Toast.makeText(getApplicationContext(),"输入正确的验证码",Toast.LENGTH_SHORT).show();
                        }

                    }
                    else{
                        Toast.makeText(getApplicationContext(),"输入相同的密码",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        textView.setText(phone.substring(0,3)+"****"+phone.substring(7,11));
    }

    private static Gson gson=new Gson();
    private Mhandler mHandler;
    Button regs;
    final OkHttpClient client = new OkHttpClient();

    private class Mhandler extends Handler {
        private WeakReference<ChangepswActivity> mActivity;
        private String code;

        public Mhandler(ChangepswActivity activity){
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==2){
                String ReturnMessage = (String) msg.obj;
                Log.i("获取的返回信息",ReturnMessage);

                code=ReturnMessage;
                SPUtil.getInstance(getApplicationContext()).putString("code", code);


                /***
                 * 在此处可以通过获取到的Msg值来判断
                 * 给出用户提示注册成功 与否，以及判断是否用户名已经存在
                 */

            }
            if(msg.what==1){
                Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(ChangepswActivity.this,MainActivity.class);
                startActivity(intent);
            }
            if(msg.what==111){
                reg.setEnabled(true);
                reg.setBackgroundResource(R.color.btn);
                reg.setText("发获取验证码");
            }
            if(msg.what==222){

                reg.setText("("+msg.obj+")秒后重新获取验证码");
            }
        }
    }
    private void postRequestCode(String phone)  {
        //建立请求表单，添加上传服务器的参数
        RequestBody formBody = new FormBody.Builder()
                .add("chan","1")
                .add("phone",phone)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/sendCode?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        mHandler.obtainMessage(2, response.body().string()).sendToTarget();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    int i=60;
    Timer timer;
    public  void timerTest() {
        //创建一个定时器
        timer = new Timer();

        //schedule方法是执行时间定时任务的方法
        timer.schedule(new TimerTask() {

            //run方法就是具体需要定时执行的任务
            @Override
            public void run() {
                if (i == 0) {
                    mHandler.obtainMessage(111).sendToTarget();
                } else {
                    i--;
                    mHandler.obtainMessage(222, i).sendToTarget();

                }

            }
        }, 200,1000);
    }
        private void postRequest(String psw)  {
        //建立请求表单，添加上传服务器的参数
        RequestBody formBody = new FormBody.Builder()
                .add("psw",psw)
                .add("phone",phone)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/changPsw?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        mHandler.obtainMessage(1, response.body().string()).sendToTarget();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
